package com.lp.rpc.registry;

import com.lp.rpc.constants.LpConstant;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * zk连接
 * @author steakLiu
 */
public class ZkConnection {
    private static ZooKeeper zoo;
    final static CountDownLatch connectionSign = new CountDownLatch(1);

    static String address = "116.198.160.39:2181,116.198.160.39:2182,116.198.160.39:2183";

    public static ZooKeeper connection(){
        if (zoo == null){
            synchronized (ZkConnection.class){
                if (zoo == null){
                    try {
                        zoo = new ZooKeeper(address, LpConstant.zkTimeOut, new Watcher() {
                            @Override
                            public void process(WatchedEvent watchedEvent) {
                                if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
                                    connectionSign.countDown();
                                }
                            }
                        });
                        connectionSign.await();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }

        return zoo;
    }

    public void close() throws InterruptedException {
        zoo.close();
    }
}
